import penentregsApi from '../../../common/api/food/penentregs.api.js'
import doT from '../../../../vendor/template/doT.js';
import { requestDict, DictionaryType } from '../../../common/dictionary/dictionary-type.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";

const LICENSE_PLATE = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;

let _vm, checkEmploy = [], employeesList = [], checkboxList = [],invtryLocatnInfo={},_personOrg=[],_suppliersList = [], recevEntries = [], saleEntries = [];
const PartnerSvcUrl = Utils.CurDomain.PartnerSvcUrl;
const addsaleTemplate = doT.template($('#addsaleorders-template').text());
const addrecevTemplate = doT.template($('#addrecev-template').text());

let _page = {
    pageSize: 10,
    pageIndex: 0,
    totalPages: -1,
};
let _pageSaleOrder= {
    pageSize: 10,
    pageIndex: 0,
    totalPages: -1,
};
let _pageCarWghTkt= {
    pageSize: 10,
    pageIndex: 0,
    totalPages: -1,
};
(function (window, document, $) {
    $(function () {
        _vm = new Vue({
            el: "#addentryrgst-form",
            data() {
                return {
                    "bizDate": moment(new Date()).format('YYYY-MM-DD'),
                    "company": {
                        "id": "",
                        "name": ""
                    },
                    "pigEntAndCheckRegId": "",
                    "pigEntAndCheckRegBillNo": "",
                    "carNo": "",
                    "sltrSupp": {
                        "id": "",
                        "name": "",
                        "numCode": "",
                        "phone": ""
                    },
                    "unldPigQty": '',
                    "penEntTime": moment(new Date()).format('YYYY-MM-DD HH:mm'),
                    "attaches": [],
                    imageList:[],
                    uploadCount: 0,
                    page: { ..._page },
                    checkEmploy: "",
                    employeesList: "",
                    checkboxList: "",
                    pageSaleOrder: { ..._pageSaleOrder },
                    pageCarWghTkt: { ..._pageCarWghTkt },
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        uploadInit();
        clickFun();
        _initCommand();
        _initCarWghTkt();
    });
    // 初始化数据
    const _initCommand = async () => {
        // 代宰户
        $('#penentregsltrSupp').select2({
            allowClear: true,
            language: "zh-CN",
            placeholder: '请选择代宰户...', //默认文字提示
            ajax: {
                url: `${Utils.CurDomain.PartnerSvcUrl}/sltrsupps/by/q`,
                dataType: 'json',
                type: 'GET',
                beforeSend: Utils.AjaxBeforeSend,
                data: function (params) {
                    return {
                        Status: true,
                        // SearchInfo: params.term,
                        PageSize: 10,
                        PageIndex: (params.page || 1) - 1,
                        ...(Utils.IsNotNull(params.term) ? { SearchInfo: params.term } : {})
                    };
                },
                cache: true,
                delay: 700,//等待用户输入完后的 在等700毫秒 进行搜索
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    let _data = data.data.items.map(item => {
                        item.text = `${item.name}(${item.numCode})`;
                        return item;
                    });
                    return {
                        results: _data,// 后台返回的数据集
                        pagination: {
                            more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
                        }
                    };
                },
                "error": async function (xhr, textStatus, errorThrown) {
                    let errorInfo = await Utils.AjaxError(xhr, textStatus, errorThrown)
                    if (Utils.IsNotNull(errorInfo)) {
                        sltrMakeAjaxCall()
                    }
                }
                // minimumInputLength: 1,
            }
        });
        $('#penentregsltrSupp').setSelectValue();
        // 选择代宰户
        $('#penentregsltrSupp').on('select2:select', async function (e) {
            _vm.sltrSupp.id = $('#penentregsltrSupp').select2('data')[0].id
            _vm.sltrSupp.numCode = $('#penentregsltrSupp').select2('data')[0].numCode
            _vm.sltrSupp.name = $('#penentregsltrSupp').select2('data')[0].name
            _vm.sltrSupp.phone = $('#penentregsltrSupp').select2('data')[0].phone
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });

        // 选择业务日期
        $('#search-date').on('click', function () {
            pick();
        });
        // 选择入圈时间
        $('#search-date-penEntTime').on('click', function () {
            isWhichTime();
        });

        // 编辑
        let ids = getUrlKey("id")
        if (Utils.IsNotNull(ids)) {
            document.title = '入圈登记 - 编辑'
            await penentregsApi.getPenentregs(ids).then(async res => {
                if(Utils.IsNotNull(res?.pigEntAndCheckRegId)){
                    await penentregsApi.getAnmlQtCertRegs(res?.pigEntAndCheckRegId).then(results=>{
                        res.pigEntAndCheckRegBillNo = results.bizFormObj.billNo;
                    })
                }
                res.bizDate = moment(res.bizFormObj.bizDate).format('YYYY-MM-DD')
                res.penEntTime = moment(res.penEntTime).format('YYYY-MM-DD HH:mm')
                Utils.SetRouterState('deliverDatas', res)
                JSON.stringify(Utils.SetSessionStorage("ids", ids))
                res.penEntEntry.map(item => {
                    item.seq = Number(item.seq) - 1
                });
                JSON.stringify(Utils.SetSessionStorage("getEntryInfo", res.penEntEntry))
            });
        }

        // 获取主表数据
        let getMainInfo = JSON.parse(Utils.GetSessionStorage("deliverDatas"))
        if (Utils.IsNotNull(getMainInfo)) {
            const propertiesToCopy = [
                "bizDate","company","pigEntAndCheckRegId","pigEntAndCheckRegBillNo",
                "carNo","sltrSupp","unldPigQty","penEntTime","attaches","imageList"
            ];
            propertiesToCopy.reduce((obj, prop) => {
                _vm[prop] = getMainInfo[prop];
            }, {});
            $('#penentregsltrSupp').select2('val', _vm.sltrSupp.id); // 假设您想根据ID设置选中值
            $('#penentregsltrSupp').next('.select2-container').find('.select2-selection__rendered').text(cutstr(`${_vm.sltrSupp.name}(${_vm.sltrSupp.numCode})`, 20));    
            // 附件
            if (Utils.IsNotNull(getMainInfo.attaches)) {
                if(Array.isArray(getMainInfo.attaches)==true){
                    _images(getMainInfo.attaches);
                }else{
                    if(getMainInfo.attaches.indexOf(',')!=-1){
                        _images(getMainInfo.attaches.split(','));
                    }else{
                        _images([getMainInfo.attaches]);
                    }
                }
            }
        }

        // 获取分录数据
        let getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        if (getEntryInfo) {
            $('#salesEntry').empty().append(addsaleTemplate(getEntryInfo));
            let totalCount = 0
            getEntryInfo.map(item => {
                totalCount += Number(item.num)
            })
            _vm.unldPigQty = totalCount
        }

        // 点击 新增分录
        $('#add-saleEntry').on("click", function (e) {
            storeSession()
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0
            location.href = `../penentregs/penentregsentry.html?index=${index}`;
        })
        // 点击 编辑分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = $(this).data('index')
            location.href = `../penentregs/penentregsentry.html?index=${index}&isEdit=true`;
        });

        // 点击 删除分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {
                            let datas = getEntryInfo.filter(item => item.seq != seq)
                            let pigDetailsInfoDetele = pigDetailsInfo.filter(item => item.pereSeq != seq)
                            // 重新排序
                            let info = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []
                            pigDetailsInfoDetele.map(item => {
                                if (Number(item.pereSeq) > seq) {
                                    item.pereSeq = Number(item.pereSeq) - 1
                                }
                            })

                            // 赋值 
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", info))

                            $('#salesEntry').empty().append(addsaleTemplate(info));
                            let totalCount = 0
                            info.map(item => {
                                totalCount += Number(item.num)
                            })
                            _vm.unldPigQty = totalCount
                            $.closeModal();
                        }
                    }
                ]
            });
        });


        // 获取收货分录数据
        let getReceveEntry = JSON.parse(Utils.GetSessionStorage("getReceveEntry"))
        if (getReceveEntry) {
            getReceveEntry.forEach(item => {
                item.isShowEdit = _vm.isShowAddRecev == true?'block':'none';
                item.isShowSale = _vm.isShowAddRecev == true?'none':'block';
            })
            $('#recevEntries').empty().append(addrecevTemplate(getReceveEntry));
        }

        // 点击 新增收货分录
        $('#add-recevEntries').on("click", function (e) {
            // 存储数据
            storeSession();
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0;
            if (_vm.company.id) {
                location.href = `../penentregs/penentregrecev.html?index=${index}&companyId=${_vm.company.id}`;
            }else{
                $.toptip('请先选择准宰登记', 'warning');
                return
            }
        })
        // 点击 编辑收货分录
        $(document).on('click', '#recevEntries div[data-flag=table-click-edit-recev]', function () {
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = $(this).data('index')
            location.href = `../penentregs/penentregrecev.html?index=${index}&companyId=${_vm.company.id}&isEdit=true`;
        });
        // 点击 删除收货分录
        $(document).on('click', '#recevEntries div[data-flag=table-click-delete-recev]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {
                            if(!getEntryInfo){
                                getReceveEntry = JSON.parse(Utils.GetSessionStorage("getReceveEntry"));
                            }
                            let datas = getReceveEntry.filter(item => item.seq != seq)
                            // 重新排序
                            let info = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []
                            // 赋值 
                            JSON.stringify(Utils.SetSessionStorage("getReceveEntry", info))
                            info.forEach(item => {
                                item.isShowEdit = _vm.isShowAddRecev == true?'block':'none';
                                item.isShowSale = _vm.isShowAddRecev == true?'none':'block';
                            })
                            $('#recevEntries').empty().append(addrecevTemplate(info));
                            $.closeModal();
                        }
                    }
                ]
            });
        });

        // 确认重量改变计算确认均重
        $(document).on('change', '#recevEntries input[data-flag=table-click-cfmWeight]', function () {
            let index = $(this).data('index')
            let recevEntries = JSON.parse(Utils.GetSessionStorage("getReceveEntry"))
            recevEntries[index].cfmWeight = $(this).val();
            let cfmWeight = Number(recevEntries[index].cfmWeight);
            let number = Number(recevEntries[index].number);
            if(cfmWeight && number){
                recevEntries[index].cfmAvgWgh = Number(cfmWeight/number).toFixed(2);
            }else{
                recevEntries[index].cfmAvgWgh = 0;
            }
            // 存入SessionStorage
            JSON.stringify(Utils.SetSessionStorage("getReceveEntry", recevEntries))
            $('#recevEntries').empty().append(addrecevTemplate(recevEntries));
        })

    }

    // 初始换准宰登记
    const _initSltrregs = () => {
        // 点击准宰登记 显示选择页面
        $(document).on('click', "#reportLead", function () {
            $("#report-contact").popup();
            $("#content").empty();
            refreshQuery();
        });
        //TODO : 员工上拉加载
        $("#iscroll").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                queryEmployeesList();
                self.loading = false;
            }, 500);   //模拟延迟
        });
        // 搜索
        $("#searchdiv form").submit(function () {
            _mainSearch();
            return false;
        }).on("input propertychange", Utils.throttle(_mainSearch, 500));
        search();

        // 选择准宰登记 复选框
        $(document).on('click', '#iscroll .weui-check__label', function (event) {
            // event.stopPropagation();   //表示阻止向父元素冒泡
            event.preventDefault();     //阻止 方法阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked')
            $(this).find("input[type='checkbox']").prop("checked", !isChecked);
            if (!isChecked == true && checkboxList.includes($(this).data("id")) == false) {
                checkboxList.push($(this).data("id"));
            } else {
                checkboxList.splice(checkboxList.indexOf($(this).data("id")), 1);
            }
            $('#subEmployees').text(`确定(${checkboxList.length})`);
            $("#choose").text(`已选择:${checkboxList.length}条`);
        });

        // 取消按钮
        $("#cancelSub").on('click', function () {
            let checkHistory = [...checkEmploy.map(item => { return item.id })] || [];// 点取消时的上一次数据
            checkboxList = checkHistory;// 上一次点 确定的数据  赋值给  选中的数据
            $('#subEmployees').text(`确定(${checkboxList.length})`);
            $("#choose").text(`已选择:${checkboxList.length}条`);
            $.closePopup();
            $('#searchInput').val("");
            $('#searchBar').removeClass("weui-search-bar_focusing");
        });

        // 确定
        $("#subEmployees").on('click', function () {
            let subData = [...checkboxList.map(item => { return [...employeesList, ...checkEmploy].find(item1 => item1.id == item); })] || [];
            checkEmploy = subData;
            let bizDateArr = [], bcarNoArr = []
            if (Utils.IsNotNull(checkEmploy)) {
                checkEmploy.map(item1 => {
                    bizDateArr.push(item1.bizFormObj.bizDate)
                    bcarNoArr.push(item1.certTkt.carNo)
                })
                const firstElement1 = bizDateArr[0];
                let flag1 = bizDateArr.every(element => element === firstElement1)
                const firstElement2 = bcarNoArr[0];
                let flag2 = bcarNoArr.every(element => element === firstElement2)
                if (!flag1) {
                    $.toptip('业务日期不同', 'warning');
                    return
                }
                if (!flag2) {
                    $.toptip('车牌号不同', 'warning');
                    return
                }
                penentregsApi.getSltrregs(checkEmploy[0].id).then(results => {
                    let { company, certTkt, sltrSupps } = results
                    let selectDptrPlc;
                    if (Utils.IsNotNull(results.certTkt.dptrPlc)) {
                        let shipRegion = results.certTkt.dptrPlc.split('|')[1].split(';');
                        selectDptrPlc = shipRegion[0] + shipRegion[1] + shipRegion[2] + (shipRegion[3] ? shipRegion[3] : '') + results.certTkt?.address
                    }
                    _vm.company.id = company.id
                    _vm.company.name = company.name
                    _vm.origin = selectDptrPlc
                    _vm.sltrregsCarNo = certTkt.carNo
                    _vm.sltrSupp = { ...sltrSupps[0] }
                    $('#penentregsltrSupp').setSelectValue(sltrSupps[0]?.id, sltrSupps[0]?.name);
                }).catch(error => {
                    console.error("An error occurred:", error);
                });
            }

            $('#searchInput').val("");
            if (Utils.IsNotNull(checkEmploy.length)) {
                $('#reportLead').val(`已选择${checkEmploy.length}条准宰登记`)
            }
            else {
                $('#reportLead').val('')
            }
            $.closePopup();
            $('#searchBar').removeClass("weui-search-bar_focusing");
        });
    }
    //查询准宰登记信息
    const refreshQuery = () => {
        let _page = {
            "searchInfo": $('#searchInput').val(),
            "pageIndex": 0,
            "totalPages": -1,
            "pageSize": 50,
        };
        _vm.page = Object.assign(_vm.page, _page);
        queryEmployeesList();
    }

    function unique(arr) {
        const res = new Map();
        return JSON.parse(JSON.stringify(arr)).filter((a) => !res.has(a.id) && res.set(a.id, 1))
    }

    // 准宰登记 输入框
    const _mainSearch = function () {
        let _page = {
            "searchInfo": $('#searchInput').val(),
            "pageIndex": 0, "totalPages": -1,
            "pageSize": 50, "status": true
        };
        _vm._data.page = Object.assign(_vm._data.page, _page);
        $("#content").empty();
        queryEmployeesList();
    };
    // 准宰登记 输入框
    const search = () => {
        let $searchBar = $('#searchBar'),
            $searchResult = $('#searchResult'),
            $searchText = $('#searchText'),
            $searchInput = $('#searchInput'),
            $searchClear = $('#searchClear'),
            $searchForm = $('#searchForm'),
            $searchCancel = $('#searchCancel');

        function hideSearchResult() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearch() {
            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearch();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $("#content").empty();
                    //refreshQuery();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResult();
            $searchInput.focus();
            $("#content").empty();
            refreshQuery()
        });
        $searchCancel.on('click', function () {
            cancelSearch();
            $("#content").empty();
            refreshQuery();
            $searchInput.blur();
        });
    }
    //准宰登记 数据源
    const queryEmployeesList = () => {
        let _data = _vm.page;
        let _list = [];
        penentregsApi.postSltrregsList(Object.assign({
            billStatus: 3,
            sort: "bizFormObj.createTime desc"
        }, _data)).then(res => {
            let _page = {
                searchInfo: $('#searchInput').val(),
                pageSize: 50,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            }
            _vm._data.page = Object.assign({}, _page);
            if (!Utils.IsNotNull($('#searchInput').val()) && _data.pageIndex == 0) {
                _list.push(...checkEmploy);
            }
            _list.push(...res.items);
            unique(_list).map(item => {
                let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="" aria-hidden="true">
                        <span>单据编号：${item.bizFormObj.billNo}</span>
                        <div>车牌号：${item.certTkt.carNo}</div>
                        <div>代宰户：${item.sltrSuppNames || ""}</div>
                        <div>登记时间：${moment(new Date(item.regTime)).format('YYYY-MM-DD HH:mm')
                    }</div>
                    </div>
                </label>`
                $("#content").append(labhtml);
            });
            checkboxList.map(item1 => $(`#${item1}`).prop("checked", true));
            employeesList = [...employeesList, ...res.items];
        });
    }
    // 保存分录以上的内容
    const storeSession = () => {
        const propertiesToCopy = [
            "bizDate","company","pigEntAndCheckRegId","pigEntAndCheckRegBillNo",
            "carNo","sltrSupp","unldPigQty","penEntTime","attaches","imageList"
        ];
        const deliverDatas = propertiesToCopy.reduce((obj, prop) => {
            obj[prop] = _vm[prop];
            return obj;
        }, {});
        
        let _attaches = [];
        $.each(_vm.imageList, function (i, v) {
            _attaches.push(v.imageId);
        });
        deliverDatas.attaches = _attaches;
        Utils.SetRouterState('deliverDatas', deliverDatas)
    }
    
    // 日期选择器
    const pick = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')
            }
        });
    }
    // 时间选择器
    function isWhichTime() {
        let years = [];
        let mouth = [];
        let date = [];
        let hours = [];
        let minite = [];
        if (!years.length && !mouth.length) {
            for (let i = 1889; i <= 2030; i++) {
                years.push({
                    label: i + "年",
                    value: i
                });
            }
        }
        if (!mouth.length) {
            mouth = costomDatePicker(mouth, 1, 13, "月")
        }
        if (!date.length) {
            date = costomDatePicker(date, 1, 32, "日")
        }
        if (!hours.length) {
            hours = costomDatePicker(hours, 0, 24, "时")
        }
        if (!minite.length) {
            minite = costomDatePicker(minite, 0, 60, "分")
        }

        weui.picker(years, mouth, date, hours, minite, {
            id: new Date(),//让每一个点击弹框得都有一个不一样得id，这样就避免了共用一个弹框得时候，打开得日期是上一次另外一个得日期回显
            defaultValue: [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate(), new Date().getHours(), new Date().getMinutes(), new Date().getSeconds()],
            onConfirm: result => {
                //result 是数组，返回得是当前选中得数，如[{lable:'2019年,value:2019},{lable:'2月,value:2}，{lable:'2号,value:2}]
                if (result.length) {
                    //yyyy-mm-dd hh:mm:ss
                    let time = result[0].value + '-' + result[1].value + '-' + result[2].value + ' ' + result[3].value + ':' + result[4].value;
                    _vm.penEntTime = time
                }
            }
        });
    }

    //自定义日期:月时分秒
    function costomDatePicker(years, startTime, endTime, str) {
        for (let j = startTime; j < endTime; j++) {
            years.push({
                label: ('' + j).length === 1 ? '0' + j + str : '' + j + str,
                value: ('' + j).length === 1 ? '0' + j : '' + j,
            });
        }
        return years;
    };

    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            window.sessionStorage.removeItem("getEntryInfo");
            window.sessionStorage.removeItem("deliverDatas");
            window.sessionStorage.removeItem("ids");
            location.href = `../penentregs/penentregslist.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                'bottom': '-6rem',
                'transition': 'all .ls ease-in'
            });
        });

        // 提交数据
        $('#informationSubmit').on("click", function (e) {
            let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
            if (!Utils.IsNotNull(_vm.bizDate)) {
                return $.toptip(`请选择业务日期!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.pigEntAndCheckRegId)) {
                return $.toptip(`请选择生猪入场与宰前检验!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.company.id)) {
                return $.toptip(`公司没有带出!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.sltrSupp.id)) {
                return $.toptip(`请选择代宰户!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.penEntTime)) {
                return $.toptip(`请选择下圈时间!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.carNo)) {
                return $.toptip(`请输入车牌号!`, 'warning');
            }
            if (Utils.IsNotNull(_vm.carNo) && !_vm.carNo.match(LICENSE_PLATE)) {
                return $.toptip(`请输入正确的车牌号!`, 'warning');
            }
            if (!Utils.IsNotNull(entries)) {
                return $.toptip(`请添加分录信息!`, 'warning');
            }
            
            savetips();
        })
    }
    // 保存
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;"><div class="addentry">是否确认保存该单据？</div></div></div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "确定", onClick: function () {
                        $.closeModal();
                        const propertiesToCopy = [
                            "bizDate","company","pigEntAndCheckRegId","pigEntAndCheckRegBillNo",
                            "carNo","sltrSupp","unldPigQty","penEntTime","attaches","imageList"
                        ];
                        const datas = propertiesToCopy.reduce((obj, prop) => {
                            obj[prop] = _vm[prop];
                            return obj;
                        }, {});
                        let ids = Utils.GetSessionStorage("ids")
                        let _attaches = [];
                        $.each(_vm.imageList, function (i, v) {
                            _attaches.push(v.imageId);
                        });
                        datas.attaches = _attaches.join(',')
                        let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) 
                        // 重新赋值
                        entries.map(item => item.seq = Number(item.seq) + 1)
                        datas.penEntEntry = [...entries]
                        if (Utils.IsNotNull(ids)) {
                            penentregsApi.putPenentregs(ids, datas).then(res => {
                                $.toptip('请求成功!', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `./penentregslist.html `;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                        else {
                            penentregsApi.postPenentregs(datas).then(res => {
                                $.toptip('请求成功!', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `./penentregslist.html `;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                    }
                }
            ]
        });
    }
    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

    // 
    const _initSaleOrder = async () => {
        //查询用户拥有的组织
        await penentregsApi.getOrgsList().then(res => {
            _personOrg = [];
            res.forEach(item => {
                if (item.optTag == 1 && item.tags.indexOf('210') !== -1) {
                    _personOrg.push(item.oId);
                }
            });
        });

        // 点击销售订单 显示选择页面
        $(document).on('click', "#saleOrderNCode", function () {
            $('#searchInputSaleOrder').val('');//筛选条件
            $("#saleOrder-contact").popup();
            $("#contentSaleOrder").empty();
            refreshQuerySaleOrder();
        });
        // 上拉加载
        $("#iscrollSaleOrder").infinite().on("infinite", function () {
            let _data = _vm.pageSaleOrder;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                queryListSaleOrder();
                self.loading = false;
            }, 500);//模拟延迟
        });
        // 搜索
        $("#searchdivSaleOrder form").submit(function () {
            _mainSearchSaleOrder();
            return false;
        }).on("input propertychange", Utils.throttle(_mainSearchSaleOrder, 500));
        searchSaleOrder();

        // 销售订单 单选框
        $(document).on('click', '#iscrollSaleOrder .weui-check__label', function (event) {
            // event.stopPropagation();   //表示阻止向父元素冒泡
            event.preventDefault();     //阻止 方法阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked')
            $(this).find("input[type='checkbox']").prop("checked", !isChecked);
            $(this).siblings().find("input[type='checkbox']").prop("checked", false);
            if(!isChecked == true) {
                _vm.saleOrderId = $(this).data("id");
                _vm.saleOrderNCode = $(this).find('.weui-cell__hddata').find('.weui-cell_billNo').data("id");
                if(!_vm.saleOrderId){
                    _vm.isShowAddRecev = true;
                }else{
                    _vm.isShowAddRecev = false;
                }
                let purchaseId = $(this).find('.weui-cell__hddata').find('.weui-cell_sapPurchaseBillNo').data("id");//采购订单ID
                let purchaseBillNo = $(this).find('.weui-cell__hddata').find('.weui-cell_sapPurchaseBillNo').data("id");//采购订单号
                let purchsOdLineNo = 10;//采购订单行项目号
                //获取采购订单详情
                $.ajax({
                    url: `${Utils.CurDomain.SAPSynUrl}/purchaseorders/${purchaseId}`,
                    dataType: 'text',
                    type: 'get',
                    headers: {
                        "Authorization": "Bearer " + Utils.GetSNAuthAT(),
                        "Content-Type": "application/json",
                        "Accept": "application/json"
                    },
                    async: false,
                    success: (result, textStatus, xhr) => {
                        let res = JSON.parse(result).data;
                        //获取供应商
                        $.ajax({
                            url: `${Utils.CurDomain.SAPSynUrl}/sapsupplier/${res.lifnr}`,
                            dataType: 'text',
                            type: 'get',
                            headers: {
                                "Authorization": "Bearer " + Utils.GetSNAuthAT(),
                                "Content-Type": "application/json",
                                "Accept": "application/json"
                            },
                            async: false,
                            success: (results, textStatus, xhr) => {
                                let resu = JSON.parse(results).data;
                                _suppliersList = [];
                                _suppliersList.push(resu);
                                let list = [];
                                let i = 0;
                                saleEntries.forEach(item => {
                                    list.push({
                                        "purchsOrderId":purchaseId,
                                        "purchsOrderNCode":purchaseBillNo,
                                        "purchsOrderLineNo":purchsOdLineNo,
                                        "suppId":_suppliersList[0].id || "",
                                        "suppNum":res.lifnr || "",
                                        "suppName":_suppliersList[0].bU_SORT1 || "",
                                        "isInternalSupp":res.zzsfnb==1?true:false,
                                        "breedBatch":item.breedBatch.id || "",
                                        "breedBatchName":item.breedBatch.name || "",
                                        "farmOrgObj":{
                                            "id":item.farmOrg.id || "",
                                            "name":item.farmOrg.name || ""
                                        },
                                        "materialObj":{
                                            "id":item.material.id || "",
                                            "numCode":item.material.numCode || "",
                                            "name":item.material.name || "",
                                            "baseMeasureUnit":item.material.baseMeasureUnit || "",
                                            "auxMeasureUnit":item.material.subMeasureUnit || ""
                                        },
                                        "number":item.count || 0,
                                        "weight":item.weight || 0,
                                        "price":item.unitPrice || 0,
                                        "carNo":item.carNo || "",
                                        "carWghTkt": {
                                            "id": "",
                                            "carNo": "",
                                            "netWeight": ''
                                        },
                                        "cfmWeight": '',
                                        "cfmAvgWgh": 0,
                                        "seq":i++,
                                        "isShowEdit":_vm.isShowAddRecev == true?'block':'none',
                                        "isShowSale":_vm.isShowAddRecev == true?'none':'block',
                                        });
                                })
                                // 存入SessionStorage
                                JSON.stringify(Utils.SetSessionStorage("getReceveEntry", list))
                                $.closePopup();
                                $('#searchBarSaleOrder').removeClass("weui-search-bar_focusing");
                                $('#recevEntries').empty().append(addrecevTemplate(list));
                            },
                            error: (xhr, textStatus, error) => {
                                $.toptip('供应商匹配失败', 'warning');
                                _suppliersList = [];
                                let list = [],j = 0;
                                saleEntries.forEach(item => {
                                    list.push({
                                        "purchsOrderId":purchaseId,
                                        "purchsOrderNCode":purchaseBillNo,
                                        "purchsOrderLineNo":purchsOdLineNo,
                                        "suppId":res.lifnr || "",
                                        "suppNum":res.lifnr || "",
                                        "suppName":"",
                                        "isInternalSupp":res.zzsfnb==1?true:false,
                                        "breedBatch":item.breedBatch.id || "",
                                        "breedBatchName":item.breedBatch.name || "",
                                        "farmOrgObj":{
                                            "id":item.farmOrg.id || "",
                                            "name":item.farmOrg.name || ""
                                        },
                                        "materialObj":{
                                            "id":item.material.id || "",
                                            "numCode":item.material.numCode || "",
                                            "name":item.material.name || "",
                                            "baseMeasureUnit":item.material.baseMeasureUnit || "",
                                            "auxMeasureUnit":item.material.subMeasureUnit || ""
                                        },
                                        "number":item.count || 0,
                                        "weight":item.weight || 0,
                                        "price":item.unitPrice || 0,
                                        "carNo":item.carNo || "",
                                        "carWghTkt": {
                                            "id": "",
                                            "carNo": "",
                                            "netWeight": ''
                                        },
                                        "cfmWeight": '',
                                        "cfmAvgWgh": 0,
                                        "seq":j++,
                                        "isShowEdit":_vm.isShowAddRecev == true?'block':'none',
                                        "isShowSale":_vm.isShowAddRecev == true?'none':'block',
                                    });
                                })
                                // 存入SessionStorage
                                JSON.stringify(Utils.SetSessionStorage("getReceveEntry", list))
                                $.closePopup();
                                $('#searchBarSaleOrder').removeClass("weui-search-bar_focusing");
                                $('#recevEntries').empty().append(addrecevTemplate(list));
                            }
                        });
                    },
                    error: (xhr, textStatus, error) => {
                        $.toptip('获取销售订单上的采购订单失败', 'warning');
                    }
                });
                
            }
        });

        // 取消按钮
        $("#cancelSaleOrder").on('click', function () {
            $.closePopup();
            $('#searchInputSaleOrder').val("");
            $('#searchBarSaleOrder').removeClass("weui-search-bar_focusing");
        });
    }

    //查询销售订单信息
    const refreshQuerySaleOrder = () => {
        let _pageSaleOrder = {
            billStatus: '',
            custName: '',
            salePerName: '',
            startDate: '1000-01-01',
            endDate: '9999-12-31',
            farmName: '',
            breedBatchName: '',
            fitlerOrgs: _personOrg,
            billNo: $(`#searchInputSaleOrder`).val(),
            sort: "createTime desc",
            pageIndex: 0,
            totalPages: -1,
            pageSize: 50,
        };
        _vm.pageSaleOrder = Object.assign(_vm.pageSaleOrder, _pageSaleOrder);
        queryListSaleOrder();
    }

    //销售订单 数据源
    const queryListSaleOrder = () => {
        let _data = _vm.pageSaleOrder;
        let _list = [];
        penentregsApi.postOrderList(_data).then(res => {
            let _page = {
                billStatus: '',
                custName: '',
                salePerName: '',
                startDate: '1000-01-01',
                endDate: '9999-12-31',
                farmName: '',
                breedBatchName: '',
                fitlerOrgs: _personOrg,
                billNo: $(`#searchInputSaleOrder`).val(),
                sort: "createTime desc",
                pageSize: 50,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            }
            _vm.pageSaleOrder = Object.assign({}, _page);
            _list.push(...res.items);
            unique(_list).map(item => {
                saleEntries=[];
                saleEntries = item.entries;
                let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="weui-cell__hddata" aria-hidden="true">
                        <span class="weui-cell_billNo" data-id="${item.billNo}">单据编号：${item.billNo}</span>
                        <div class="weui-cell_orgName" data-id="${item.orgName}">公司：${item.orgName}</div>
                        <div class="weui-cell_custName" data-id="${item.custName}">客户：${item.custName}</div>
                        <div class="weui-cell_sapPurchaseBillNo" data-id="${item.sapPurchaseBillNo}">采购订单编号：${item.sapPurchaseBillNo}</div>
                    </div>
                </label>`;
                $("#contentSaleOrder").append(labhtml);
            });
        });
    }

    // 销售订单 输入框
    const _mainSearchSaleOrder = function () {
        let _page = {
            billStatus: '',
            custName: '',
            salePerName: '',
            startDate: '1000-01-01',
            endDate: '9999-12-31',
            farmName: '',
            breedBatchName: '',
            fitlerOrgs: _personOrg,
            billNo: $(`#searchInputSaleOrder`).val(),
            sort: "createTime desc",
            pageIndex: 0, 
            totalPages: -1,
            pageSize: 50, 
        };
        _vm.pageSaleOrder = Object.assign(_vm.pageSaleOrder, _page);
        $("#contentSaleOrder").empty();
        queryListSaleOrder();
    };
    
    // 销售订单 输入框
    const searchSaleOrder = () => {
        let $searchBar = $('#searchBarSaleOrder'),
            $searchResult = $('#searchResultSaleOrder'),
            $searchText = $('#searchTextSaleOrder'),
            $searchInput = $('#searchInputSaleOrder'),
            $searchClear = $('#searchClearSaleOrder'),
            $searchForm = $('#searchFormSaleOrder'),
            $searchCancel = $('#searchCancelSaleOrder');

        function hideSearchResult() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearch() {
            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearch();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $("#contentSaleOrder").empty();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResult();
            $searchInput.focus();
            $("#contentSaleOrder").empty();
            refreshQuerySaleOrder()
        });
        $searchCancel.on('click', function () {
            cancelSearch();
            $("#contentSaleOrder").empty();
            refreshQuerySaleOrder();
            $searchInput.blur();
        });
    }

    // 初始生猪入场与宰前检验
    const _initCarWghTkt = () => {
        let index='';
        // 点击生猪入场与宰前检验 显示选择页面
        $(document).on('click', '#pigEntAndCheckRegBillNo', function () {
            index = $(this).data('index')
            $('#searchInputCarWghTkt').val(_vm.sltrregsCarNo);//筛选条件
            $("#carWghTkt-contact").popup();
            $("#contentCarWghTkt").empty();
            refreshQueryCarWghTkt();
        });
        // 上拉加载
        $("#iscrollCarWghTkt").infinite().on("infinite", function () {
            let _data = _vm.pageCarWghTkt;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                queryListCarWghTkt();
                self.loading = false;
            }, 500);//模拟延迟
        });
        // 搜索
        $("#searchdivCarWghTkt form").submit(function () {
            _mainSearchCarWghTkt();
            return false;
        }).on("input propertychange", Utils.throttle(_mainSearchCarWghTkt, 500));
        searchCarWghTkt();

        // 车辆过磅单 单选框
        $(document).on('click', '#iscrollCarWghTkt .weui-check__label', function (event) {
            // event.stopPropagation();   //表示阻止向父元素冒泡
            event.preventDefault();     //阻止 方法阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked')
            $(this).find("input[type='checkbox']").prop("checked", !isChecked);
            $(this).siblings().find("input[type='checkbox']").prop("checked", false);
            if(!isChecked == true) {
                _vm.pigEntAndCheckRegId = $(this).data("id");
                _vm.pigEntAndCheckRegBillNo = $(this).find('.weui-cell__hddata').find('.weui-cell_billNo').data("id");
                _vm.company.id = $(this).find('.weui-cell__hddata').find('.weui-cell_company').data("id");
                _vm.company.name = $(this).find('.weui-cell__hddata').find('.weui-cell_company').data("name");
                _vm.carNo = $(this).find('.weui-cell__hddata').find('.weui-cell_carNo').data("id");
                _vm.sltrSupp.id = $(this).find('.weui-cell__hddata').find('.weui-cell_sltrSupps').data("id");
                _vm.sltrSupp.name = $(this).find('.weui-cell__hddata').find('.weui-cell_sltrSupps').data("name");
                _vm.sltrSupp.numCode = $(this).find('.weui-cell__hddata').find('.weui-cell_sltrSupps').data("numcode");
                _vm.sltrSupp.phone = $(this).find('.weui-cell__hddata').find('.weui-cell_sltrSupps').data("phone");
                $('#penentregsltrSupp').select2('val', _vm.sltrSupp.id); // 假设您想根据ID设置选中值
                $('#penentregsltrSupp').next('.select2-container').find('.select2-selection__rendered').text(cutstr(`${_vm.sltrSupp.name}(${_vm.sltrSupp.numCode})`, 20));
                $.closePopup();
                $('#searchBarCarWghTkt').removeClass("weui-search-bar_focusing");
                // 存入SessionStorage
                JSON.stringify(Utils.SetSessionStorage("getReceveEntry", recevEntries))
                $('#recevEntries').empty().append(addrecevTemplate(recevEntries));
            }
        });

        // 取消按钮
        $("#cancelCarWghTkt").on('click', function () {
            $.closePopup();
            $('#searchInputCarWghTkt').val("");
            $('#searchBarCarWghTkt').removeClass("weui-search-bar_focusing");
        });
    }

    //查询车辆过磅单信息
    const refreshQueryCarWghTkt = () => {
        let _pageCarWghTkt = {
            billStatus: [3],
            startDate: '1000-01-01',
            endDate: '9999-12-31',
            billNo: $(`#searchInputCarWghTkt`).val(),
            sltrSuppName: '',
            regStaffName: '',
            carNo: '',
            no: '',
            penEntRegBillNo: '',
            isEnterPen: '',
            regOrderNo: '',
            sort: "bizFormObj.createTime desc",
            pageIndex: 0,
            totalPages: -1,
            pageSize: 50,
        };
        _vm.pageCarWghTkt = Object.assign(_vm.pageCarWghTkt, _pageCarWghTkt);
        queryListCarWghTkt();
    }

    //车辆过磅单 数据源
    const queryListCarWghTkt = () => {
        let _data = _vm.pageCarWghTkt;
        let _list = [];
        penentregsApi.postPigEntAndCheckRegList(_data).then(res => {
            let _page = {
                billStatus: [3],
                startDate: '1000-01-01',
                endDate: '9999-12-31',
                billNo: $(`#searchInputCarWghTkt`).val(),
                sltrSuppName: '',
                regStaffName: '',
                carNo: '',
                no: '',
                penEntRegBillNo: '',
                isEnterPen: '',
                regOrderNo: '',
                sort: "bizFormObj.createTime desc",
                pageSize: 50,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            }
            _vm.pageCarWghTkt = Object.assign({}, _page);
            _list.push(...res.items);
            unique(_list).map(item => {
                let sltrSuppsStr='';
                if(Utils.IsNotNull(item?.sltrSupps[0]?.numCode)){
                    sltrSuppsStr=`${item?.sltrSupps[0]?.name||''}(${item?.sltrSupps[0]?.numCode||''})`;
                }else{
                    sltrSuppsStr=`${item?.sltrSupps[0]?.name||''}`;
                }
                let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="weui-cell__hddata" aria-hidden="true">
                        <span class="weui-cell_billNo" data-id="${item.bizFormObj.billNo}">单据编号：${item.bizFormObj.billNo}</span>
                        <div class="weui-cell_company" data-id="${item.companyId}" data-name="${item.companyName}">公司：${item.companyName}</div>
                        <div class="weui-cell_carNo" data-id="${item.carNo}">车牌号：${item.carNo}</div>
                        <div class="weui-cell_sltrSupps" data-id="${item?.sltrSupps[0]?.id||''}" data-name="${item?.sltrSupps[0]?.name||''}" data-numcode="${item?.sltrSupps[0]?.numCode||''}" data-phone="${item?.sltrSupps[0]?.phone||''}">代宰户：${sltrSuppsStr}</div>
                    </div>
                </label>`;
                $("#contentCarWghTkt").append(labhtml);
            });
        });
    }

    // 车辆过磅单 输入框
    const _mainSearchCarWghTkt = function () {
        let _page = {
            billStatus: [3],
            startDate: '1000-01-01',
            endDate: '9999-12-31',
            billNo: $(`#searchInputCarWghTkt`).val(),
            sltrSuppName: '',
            regStaffName: '',
            carNo: '',
            no: '',
            penEntRegBillNo: '',
            isEnterPen: '',
            regOrderNo: '',
            sort: "bizFormObj.createTime desc",
            pageIndex: 0, 
            totalPages: -1,
            pageSize: 50, 
        };
        _vm.pageCarWghTkt = Object.assign(_vm.pageCarWghTkt, _page);
        $("#contentCarWghTkt").empty();
        queryListCarWghTkt();
    };
    
    // 车辆过磅单 输入框
    const searchCarWghTkt = () => {
        let $searchBar = $('#searchBarCarWghTkt'),
            $searchResult = $('#searchResultCarWghTkt'),
            $searchText = $('#searchTextCarWghTkt'),
            $searchInput = $('#searchInputCarWghTkt'),
            $searchClear = $('#searchClearCarWghTkt'),
            $searchForm = $('#searchFormCarWghTkt'),
            $searchCancel = $('#searchCancelCarWghTkt');

        function hideSearchResult() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearch() {
            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearch();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $("#contentCarWghTkt").empty();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResult();
            $searchInput.focus();
            $("#contentCarWghTkt").empty();
            refreshQueryCarWghTkt()
        });
        $searchCancel.on('click', function () {
            cancelSearch();
            $("#contentCarWghTkt").empty();
            refreshQueryCarWghTkt();
            $searchInput.blur();
        });
    }

    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                if (!isMobile() && files.length > 0) {
                    $.toptip('请使用手机拍照上传！', 'warning');
                    return false;
                }
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: async function () {
                const file = this;
                let suffix = this.name.split('.').pop().toLowerCase(); //截取附件后缀
                let name = this.name.slice(0, 11 - (suffix.length) - 1); //计算截取文件的11位字符
                let newName = name + '.' + suffix
                let file1 = publicFileDraw(newName, _vm);
                // 在这里添加日期和地点水印
                const currentDate = moment(new Date()).format('YYYY-MM-DD')
                const currentTime = moment(new Date()).format('HH:mm:ss')
                const locationWatermark = $('#addressInfo').text()
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const image = new Image();
                image.src = window.URL.createObjectURL(file);

                if (!Utils.IsNotNull(locationWatermark)) {
                    $.toptip('定位失败!', 'warning');
                    $.hideLoading();
                    $('#uploaderFiles').last().empty()
                    return
                }
                image.onload = function () {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    // 在canvas上绘制原始图片
                    context.drawImage(image, 0, 0);

                    // 添加水印，支持换行
                    const watermarkText = currentDate + ' ' + currentTime + '\n' + locationWatermark;
                    context.font = '700 ' + 80 + 'px Arial';
                    context.fillStyle = 'white';

                    // 在指定位置绘制文本
                    const x = 10;
                    const y = image.height - 160;
                    drawWrappedText(context, watermarkText, x, y, 200, 130);  // 调用自定义函数

                    // 将canvas转为Blob
                    canvas.toBlob(function (blob) {
                        const formData = new FormData();
                        formData.append('apiobjfile', blob, file1);
                        _uploadFileDraw(formData, file, _vm);
                    }, file.type || 'image/png');  // 使用原始图片的类型或默认为PNG
                }
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.imageList = _vm.imageList.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }
    // 自定义函数，用于在Canvas上绘制换行的文本
    function drawWrappedText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split('\n');
        var line = '';
        var yOffset = 0;

        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            var testLine = line + word + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;

            if (testWidth > maxWidth && i > 0) {
                context.fillText(line, x, y + yOffset);
                line = word + ' ';
                yOffset += lineHeight;
            } else {
                line = testLine;
            }
        }

        context.fillText(line, x, y + yOffset);
    }
    function isMobile() {
        return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    }
    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(async res => {
            if (res.isSucceed) {
                let imageurl = await requestFilePath(res.data)
                let _list = _vm.imageList;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: imageurl.data,
                });
                _vm.imageList = _list;
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.imageList[i].id);
                    $(this).attr('data-image-id', _vm.imageList[i].imageId);
                    $(this).attr('data-url', _vm.imageList[i].url);
                    $(this).css({ 'background-image': `url(${_vm.imageList[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.uploadCount = --_vm.uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }
    // 编辑回显 66
    const _images = async (file) => {
        _vm.imageList=[];
        let _imag = file;
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then(_res => {
                    _vm.imageList.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i],
                    });
                    if (_res.isSucceed) {
                        let _li;
                        _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.uploadCount = _sun;
        }
    }


})(window, document, jQuery)


